package org.example.projecttwo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.projecttwo.entity.Comment;
import org.example.projecttwo.entity.dto.content.request.CommentQueryDTO;
import org.example.projecttwo.entity.dto.content.request.ContentWithCommentCountDTO;
import org.example.projecttwo.mapper.CommentMapper;
import org.example.projecttwo.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author nn
 * @since 2025-11-01
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public IPage<Comment> pageByQuery(Page<Comment> page, CommentQueryDTO queryDTO) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();

        // 内容类型筛选
        if (queryDTO.getContentType() != null) {
            queryWrapper.eq(Comment::getContentType, queryDTO.getContentType());
        }

        // 内容ID筛选
        if (queryDTO.getContentId() != null) {
            queryWrapper.eq(Comment::getContentId, queryDTO.getContentId());
        }

        // 用户ID筛选
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(Comment::getUserId, queryDTO.getUserId());
        }

        // 评论状态筛选（默认查询正常状态）
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Comment::getStatus, queryDTO.getStatus());
        } else {
            queryWrapper.eq(Comment::getStatus, 0); // 假设0为正常状态
        }

        // 内容关键词筛选
        if (queryDTO.getKeyword() != null && !queryDTO.getKeyword().isEmpty()) {
            queryWrapper.like(Comment::getContent, queryDTO.getKeyword());
        }

        // 时间范围筛选
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (queryDTO.getStartTime() != null && !queryDTO.getStartTime().isEmpty()) {
            LocalDateTime start = LocalDateTime.parse(queryDTO.getStartTime(), formatter);
            queryWrapper.ge(Comment::getCreateTime, start);
        }
        if (queryDTO.getEndTime() != null && !queryDTO.getEndTime().isEmpty()) {
            LocalDateTime end = LocalDateTime.parse(queryDTO.getEndTime(), formatter);
            queryWrapper.le(Comment::getCreateTime, end);
        }

        // 父评论ID筛选（查询回复）
        if (queryDTO.getParentId() != null) {
            queryWrapper.eq(Comment::getParentId, queryDTO.getParentId());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(Comment::getCreateTime);

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeCommentAndChildren(Long commentId) {
        // 1. 查询所有子评论ID（包括所有层级）
        List<Long> allCommentIds = new ArrayList<>();
        allCommentIds.add(commentId);
        findAllChildren(commentId, allCommentIds);

        // 2. 批量删除
        int deleteCount = baseMapper.deleteBatchIds(allCommentIds);
        return deleteCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeCommentsAndChildren(List<Long> commentIds) {
        if (commentIds == null || commentIds.isEmpty()) {
            return 0;
        }

        // 1. 收集所有评论ID（包括子评论）
        List<Long> allCommentIds = new ArrayList<>();
        for (Long id : commentIds) {
            allCommentIds.add(id);
            findAllChildren(id, allCommentIds);
        }

        // 2. 批量删除
        int deleteCount = baseMapper.deleteBatchIds(allCommentIds);
        return deleteCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int clearByContentTypeAndId(Integer contentType, Long contentId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getContentType, contentType)
                .eq(Comment::getContentId, contentId);

        return baseMapper.delete(queryWrapper);
    }

    @Override
    public IPage<ContentWithCommentCountDTO> pageContentWithCommentCount(
            Page<ContentWithCommentCountDTO> page,
            Integer contentType,
            String keyword) {
        return commentMapper.selectContentWithCommentCount(page, contentType, keyword);
    }

    @Override
    public IPage<Comment> pageReplies(Page<Comment> page, Long parentId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, parentId)
                .orderByAsc(Comment::getCreateTime);

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean existsById(Long id) {
        return baseMapper.exists(new LambdaQueryWrapper<Comment>().eq(Comment::getId, id));
    }

    /**
     * 递归查询所有子评论ID
     */
    private void findAllChildren(Long parentId, List<Long> allCommentIds) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, parentId);
        List<Comment> children = baseMapper.selectList(queryWrapper);

        for (Comment child : children) {
            allCommentIds.add(child.getId());
            findAllChildren(child.getId(), allCommentIds); // 递归查询子评论的子评论
        }
    }
}